package org.openCage.artig;

import org.openCage.artig.stjx.*;
import org.openCage.io.IOUtils;
import org.openCage.io.fspath.FSPath;
import org.openCage.lang.errors.Unchecked;

import java.io.FileWriter;
import java.io.IOException;

public class CalcDeployed {
    private ArtigLogic artig;

    public CalcDeployed( ArtigLogic artig) {
        this.artig = artig;
    }

    public Deployed calc( ModuleRef mod  ) {
        Deployed deployed = new Deployed();

        deployed.setArtifact( artig.get( mod ).getArtifact());

        addArtifactInfo( deployed, deployed.getArtifact());

        return deployed;
    }

    private void addArtifactInfo( Deployed deployed, Artifact arti ) {
        for (ArtifactRef ref : arti.getDepends() ) {
            if ( !included( deployed, ref ) ) {
                Artifact newArti = artig.find( ref );
                deployed.getDependencies().add( newArti );
                addArtifactInfo( deployed, newArti );
            }
        }

        for ( Licence licence : deployed.getLicences() ) {
            if ( licence.getName().equals( arti.getLicence() )) {
                return;
            }
        }

        deployed.getLicences().add( artig.findLicence( arti.getLicence() ));
    }

    private boolean included( Deployed deployed, ArtifactRef ref ) {
        for ( Artifact arti : deployed.getDependencies() ) {
            if ( ArtigLogic.is( arti, ref )) {
                return true;
            }
        }

        return false;
    }

    public void generate() {

        //FSPath rootPom = artig.getRootPath().add( "dependencies.xml" );
        FSPath rootPom = artig.getRootPath().add( "build", "modules", "foo.xml" );

        IOUtils.ensurePath( rootPom );

        FileWriter writer = null;

        for ( ModuleRef mod : artig.getProject().getModules() ) {
            //FSPath modPom = artig.getRootPath().add( "build", "modules", mod.getName(), "META-INF", "META-INF", mod.getName() + ".artig" );
            FSPath modPom = artig.getRootPath().add( "modules", mod.getName(), "src", "main", "resources", "META-INF", mod.getName() + ".artig" );

            IOUtils.ensurePath( modPom );

            try {
                writer = new FileWriter( modPom.toFile() );

                Artig descr = new Artig();
                descr.setKind( calc( mod ) );
                descr.setVersion("0.1");    // TODO

                writer.write( ArtigToXML.toStringArtig("", descr ));

            } catch (IOException e) {
                throw Unchecked.wrap( e );
            } finally {
                IOUtils.closeQuietly( writer );
            }

        }

    }

}
